package cn.keepme.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.keepme.common.consts.PublicOPCode;
import cn.keepme.common.consts.PublicParams;

/**
 * 权限控制过滤器
 * 
 * @author pan
 */
public class SecurityFilter implements Filter {
	
	public static Log log = LogFactory.getLog(SecurityFilter.class);
	public  FilterConfig config;

	public FilterConfig getConfig() {
		return config;
	}

	public void setConfig(FilterConfig config) {
		this.config = config;
	}

	// 实现初始化方法
	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config=config;
	}
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, 
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session=request.getSession(false);
	/*  
	 * HttpSession session = request.getSession(ture)
		如果服务器上没有session就创建一个新的session，如果有就取得session。
		HttpSession session = request.getSession(false)
		如果服务器上没有session也不创建新的,返回null。 */
		
		// 获取当前访问的URI(带着项目根目录)
		String currentURL = request.getRequestURL().toString();
		String contextPath= request.getContextPath(); //项目根目录
		
		// 如果url中有关键字s1则替换成s2
//		String s1 = "error.do";
//		if (currentURL.contains(s1)) {
//			String s2 = "www.baidu.com";
//			response.sendRedirect(currentURL.replace(s1, s2));
//			return;
//		}
		log.info("currentURL1 ==<" + currentURL + ">");
		
		if (currentURL.lastIndexOf("/") >= 0) {
			currentURL = currentURL.substring(currentURL.lastIndexOf("/") + 1);
		}
		
		log.info("currentURL2 ==<" + currentURL + ">");
		
		// 设置输入输出均为UTF-8编码格式
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		
		// 过滤用户访问行为
		if (!currentURL.startsWith("error.do")) {		
			if(!isAllowIp(request)){
				response.sendRedirect(contextPath+"/error.do");
				return;
			}
		}
		
		request.setAttribute("exp", PublicOPCode.getSerialTime12());
		
//		log.info("FilterConfig= "+config);
/*
		String[] noFilters={};
		String noFilterStr=config.getInitParameter("noFilter");
		if(noFilterStr!=null && !noFilterStr.equals("")){
			noFilters=noFilterStr.split(",");
		}
		List<String> list=new ArrayList<String>();
		for(String noFilter : noFilters){
			list.add(contextPath+noFilter.trim());
		}
		
		if(!list.contains(currentURL)){
			//这里是要过滤的代码
			if(session==null){
				response.sendRedirect(contextPath+"/index.jsp");
				return;
			}else if(session.getAttribute("adminSessionBean")==null){
				response.sendRedirect(contextPath+"/index.jsp");
				return;
			}
		}
*/
		// 将控制器传向下一个filter  
		try {
			filterChain.doFilter(request, response);
		} catch (ServletException sx) {
			log.error("error occurs", sx);
		} catch (IOException iox) {
			log.error("error occurs", iox);
		}
	}

	// 实现销毁方法 
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		this.config = null; 
	}
	
	/**
     * 判断是否通过信任的网关IP过来的请求
     * @return
     */
    public boolean isAllowIp(HttpServletRequest request){
    	if (PublicParams.ALLOWIPS.contains(getClientRealIP(request)))
		{
    		return true;
		}
		return false;
    }
	/**
	 * 获取访问IP
	 * @param request
	 * @return
	 */
	private String getClientRealIP(HttpServletRequest request) {
		String ip = request.getRemoteAddr();
		if (ip.trim().equals("127.0.0.1") || ip.trim().equals("192.168.1.72"))// 如果是从Apache前端代理过来的请求，则从头中取源IP
		{
			ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (ip.indexOf(",") >= 0) // 存在逗号，有多个IP，取第一个
			{
				// ip = ip.substring(0, ip.indexOf(","));
				ip = ip.substring(ip.lastIndexOf(",") + 1);
			}
		}
		System.out.println("获取到的从反向代理IP为：" + ip);
		return ip.trim();
	}

}
